import 'dart:io';
import 'package:casdon/core/logger/log.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

// 常驻内存 Provider
final cameraProvider = AsyncNotifierProvider<CameraNotifier, String?>(
  () => CameraNotifier(),
);

class CameraNotifier extends AsyncNotifier<String?> {
  final ImagePicker _picker = ImagePicker();

  @override
  Future<String?> build() async {
    // 初始化可以为空
    return null;
  }

  // 拍照并保存本地
  Future<String?> takePhoto() async {
    if (state.isLoading) return null;

    state = const AsyncValue.loading();

    state = await AsyncValue.guard(() async {
      final XFile? photo = await _picker.pickImage(
        source: ImageSource.camera,
        imageQuality: 90,
        preferredCameraDevice: CameraDevice.rear,
      );

      if (photo == null) return null; // 用户取消拍照

      final appDir = await getApplicationDocumentsDirectory();
      final fileName = path.basename(photo.path);
      final _ = await File(photo.path).copy('${appDir.path}/$fileName');
      final filePath = "${appDir.path}/$fileName";
      Log.i("拍照存储：$filePath");
      return filePath;
    });
    return state.value;
  }

  // 可选：获取上一次拍照保存的文件
  String? get lastPhotoPath => state.value;
}
